package com.example.ribbon.rules;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

import java.util.concurrent.ThreadLocalRandom;

/**
 * @author 莫磊
 * @date 2025/8/21
 * @description
 */
@Configuration
public class UserRuleConfig {

    @Bean
    public ReactorServiceInstanceLoadBalancer ribbonRule(ServiceInstanceListSupplier supplier) {
        // return new RandomRule();
        return new UserRule("USER-SERVICE", supplier);
    }

    class UserRule implements ReactorServiceInstanceLoadBalancer {
        private final String serviceId;
        private final ServiceInstanceListSupplier supplier;

        public UserRule(String serviceId, ServiceInstanceListSupplier supplier) {
            this.serviceId = serviceId;
            this.supplier = supplier;
        }

        @Override
        public Mono<Response<ServiceInstance>> choose(Request request) {
            // 自定义的规则实现
            return supplier.get().next().map(instances -> {
                if (instances.isEmpty()) {
                    return new EmptyResponse();
                }
                int idx = ThreadLocalRandom.current().nextInt(instances.size());
                return new DefaultResponse(instances.get(1));
            });
        }
    }


}
